<template>
  <uni-popup ref="popupRef" type="center" :is-mask-click="props.maskClickClose" :mask-background-color="props.maskBackgroundColor" @change="onPopupChange">
 <view
      class="common-popup-content"
      :class="{ 'use-background-image': props.useBackgroundImage }"
      :style="{
        width: props.popupWidth,
        backgroundColor: props.useBackgroundImage ? 'transparent' : props.backgroundColor // 如果用背景图，背景色设为透明
      }"
    >      <!-- 可选的右上角关闭图标 -->
      <view v-if="props.showCloseIcon" class="close-icon-wrapper" @click.stop="handleCloseIconClick">
        <uni-icons type="closeempty" size="22" :color="props.closeIconColor"></uni-icons>
      </view>

      <!-- 可选的顶部图标 -->
      <image v-if="props.iconUrl" :src="props.iconUrl" class="popup-icon" :style="{ width: props.iconSize, height: props.iconSize, marginBottom: props.iconMarginBottom }" mode="aspectFit" />

      <!-- 可选的标题 -->
      <text v-if="props.title" class="popup-title" :style="{ color: props.titleColor, fontSize: props.titleFontSize, fontWeight: props.titleFontWeight }">{{ props.title }}</text>

      <!-- 主要内容区域 - 使用默认插槽 -->
      <view class="popup-main-content" :style="{ color: props.contentColor, fontSize: props.contentFontSize, textAlign: props.contentTextAlign }">
        <slot></slot>
      </view>

      <!-- 按钮区域 -->
      <view class="popup-actions" v-if="!hasSlot('actions') && (props.showConfirmButton || props.showCancelButton)">
        <button
          v-if="props.showCancelButton"
          class="popup-button cancel-button"
          :style="props.cancelButtonStyle"
          @click.stop="handleCancel"
        >
          {{ props.cancelText }}
        </button>
        <button
          v-if="props.showConfirmButton"
          class="popup-button confirm-button"
          :style="props.confirmButtonStyle"
          :class="{ 'full-width': !props.showCancelButton && props.showConfirmButton }"
          @click.stop="handleConfirm"
        >
          {{ props.confirmText }}
        </button>
      </view>
      <!-- 自定义按钮区域 - 使用具名插槽 -->
      <view class="popup-actions" v-else-if="hasSlot('actions')">
        <slot name="actions"></slot>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref, useSlots, watch } from 'vue';

// --- 类型定义 ---
interface UniPopupInstance {
  open: (args?: any) => void;
  close: () => void;
}

interface UniPopupChangeEvent {
  show: boolean;
  type?: string;
}

interface ButtonStyle {
  backgroundColor?: string;
  color?: string;
  border?: string;
  width?: string;
  [key: string]: any; // 允许其他 CSS 属性
}

// --- Props 定义 ---
// 使用 interface 定义 Props 类型，便于维护
interface Props {
  popupWidth?: string;
  backgroundColor?: string;
  maskClickClose?: boolean;
  maskBackgroundColor?: string;
  showCloseIcon?: boolean;
  closeIconColor?: string;
  iconUrl?: string;
  iconSize?: string;
  iconMarginBottom?: string;
  title?: string;
  titleColor?: string;
  titleFontSize?: string;
  titleFontWeight?: string | number;
  contentColor?: string;
  contentFontSize?: string;
  contentTextAlign?: 'left' | 'center' | 'right' | 'justify';
  showConfirmButton?: boolean;
  confirmText?: string;
  confirmButtonStyle?: ButtonStyle;
  showCancelButton?: boolean;
  cancelText?: string;
  cancelButtonStyle?: ButtonStyle;
}

// 使用 withDefaults 提供默认值
const props = withDefaults(defineProps<Props>(), {
  popupWidth: '600rpx',
  backgroundColor: '#007AFF',
  maskClickClose: false,
  maskBackgroundColor: 'rgba(0,0,0,0.4)',
  showCloseIcon: false,
  closeIconColor: '#FFFFFF',
  iconUrl: '',
  iconSize: '100rpx',
  iconMarginBottom: '20rpx',
  title: '',
  titleColor: '#FFFFFF',
  titleFontSize: '36rpx',
  titleFontWeight: 'bold',
  contentColor: '#FFFFFF',
  contentFontSize: '30rpx',
  contentTextAlign: 'center',
  showConfirmButton: true,
  confirmText: '确定',
  confirmButtonStyle: () => ({
    backgroundColor: '#FFFFFF',
    color: '#007AFF'
  }),
  showCancelButton: false,
  cancelText: '取消',
  cancelButtonStyle: () => ({
    backgroundColor: '#FFFFFF',
    color: '#007AFF',
  }),
  useBackgroundImage: false, // 默认不使用背景图 (或者 true，如果您希望它默认显示)
});

// --- Emits 定义 ---
const emit = defineEmits<{
  (e: 'confirm'): void;
  (e: 'cancel'): void;
  (e: 'closeByIcon'): void;
  (e: 'change', value: boolean): void; // uni-popup @change 事件
  (e: 'close'): void; // 自定义弹窗关闭事件
}>();

// --- Refs ---
const popupRef = ref<UniPopupInstance | null>(null); // 注意这里 ref 的命名要和模板中 ref="popupRef" 一致

// --- 方法 ---
const open = (args?: any): void => {
  popupRef.value?.open(args);
};

const close = (): void => {
  popupRef.value?.close();
};

const handleConfirm = (): void => {
  emit('confirm');
};

const handleCancel = (): void => {
  emit('cancel');
  close(); // 取消一般总是关闭弹窗
};

const handleCloseIconClick = (): void => {
  emit('closeByIcon');
  close();
};

const onPopupChange = (e: UniPopupChangeEvent): void => {
  emit('change', e.show);
  if (!e.show) {
    emit('close'); // 当 uni-popup 关闭时，也触发自定义的 close 事件
  }
};

// --- 插槽检查 ---
const slots = useSlots();
const hasSlot = (name: string = 'default'): boolean => {
  return !!slots[name];
};

// --- 暴露给父组件的实例方法 ---
defineExpose({
  open,
  close
});

</script>

<style scoped>
.common-popup-content {
  border-radius: 20rpx;
  padding: 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  /* 默认不设置背景图，由 :style 中的 backgroundColor 控制 */
}

.common-popup-content.use-background-image {
  background-image: url('/static/loading_background.png'); /* 您的背景图路径 */
  background-size: cover; /* 或 contain, 100% 100% 等 */
  background-position: center;
  background-repeat: no-repeat;
}

.close-icon-wrapper {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  padding: 10rpx;
  z-index: 10;
}

.popup-icon {
  /* width, height, margin-bottom now controlled by props */
}

.popup-title {
  /* font-size, color, font-weight now controlled by props */
  margin-bottom: 30rpx;
  text-align: center;
}

.popup-main-content {
  /* font-size, color, text-align now controlled by props */
  margin-bottom: 40rpx;
  width: 100%;
  line-height: 1.5;
}

.popup-actions {
  display: flex;
  justify-content: space-around;
  width: 100%;
  box-sizing: border-box;
}

.popup-actions ::v-deep .popup-button, /* For buttons inside named slot */
/* CommonPopup.vue */
.popup-button {
  flex: 1;
  margin: 0 15rpx; /* 按钮间距 */
  padding: 18rpx 0; /* 默认padding */
  height: auto;     /* 高度自适应内容 */
  line-height: 1.5; /* 默认行高 */
  font-size: 32rpx; /* 默认字体大小 */
  border-radius: 10rpx;
  text-align: center;
  border: none;
  box-sizing: border-box;
  /* 其他基础样式 */
}
.popup-button::after {
    border: none;
}
.popup-actions ::v-deep .popup-button::after, /* Remove button border */

.popup-button.confirm-button.full-width {
  margin: 0 auto; /* Center it */
  width: 80%; /* Or specific width */
  flex-grow: 0; /* Prevent stretching in flex */
}
</style>
